/*
 * led.c
 *
 *  Created on: Nov 13, 2021
 *      Author: Jinming
 */
#include <string.h>
#include "timer_2ms.h"
#include "led.h"
#include "log.h"

#define LED_NUM		1

typedef struct
{
	UINT16 hCnt;				//计数使用, 步长10ms
	UINT16 hOnCnt;				//亮灯计数使用, 步长10ms
	UINT16 hCount;				//总计数使用, 步长10ms

	GPIO_TypeDef *pGpio;
	UINT16 hPin;
}Led_t;

static Led_t gs_tLed[LED_NUM];

static void led_loop(Led_t *pHdl)
{
	pHdl->hCnt++;
	if(pHdl->hCnt >= pHdl->hCount)
	{
		pHdl->hCnt = 0;
		HAL_GPIO_WritePin(pHdl->pGpio, pHdl->hPin, 1);
	}
	else if(pHdl->hCnt == pHdl->hOnCnt)
	{
		HAL_GPIO_WritePin(pHdl->pGpio, pHdl->hPin, 0);
	}
}

static void led_scan(void *param)
{
	for(UINT8 i = 0; i < LED_NUM; i++)
	{
		led_loop(&gs_tLed[i]);
	}
}

void led_set(UINT8 ledId, UINT16 ledonTime, UINT16 ledoffTime)
{
	gs_tLed[ledId].hOnCnt = ledonTime;
	gs_tLed[ledId].hCount = ledonTime + ledoffTime;
}

INT32 led_init(void)
{
	memset(&gs_tLed, 0, sizeof(Led_t) * LED_NUM);
	gs_tLed[0].hCount = 100;
	gs_tLed[0].hOnCnt = 50;
	gs_tLed[0].pGpio = G_LED_GPIO_Port;
	gs_tLed[0].hPin = G_LED_Pin;

	TIMER_ERR timer = timer_reg_fun("Led", 5, led_scan, NULL);
	if(timer != TIMER_REG_OK)
	{
		LOGE("Led", "led register error");
		return -1;
	}

	return 0;
}
